package com.weishi.project.mcs8;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.config.BeanContext;
import com.weishi.project.mcs8.vo.DeviceVo;
import com.weishi.project.speedometer.service.ISpeedometerService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 获取外部服务器资源
 */
public class Mcs8Cilent {

    Environment environment;

    Logger logger = Logger.getLogger("Mcs8Cilent");

    private Mcs8Cilent() {
        this.environment = BeanContext.getApplicationContext().getBean(Environment.class);
        webapi_url = environment.getProperty("mcs8.webapi");
        streaming_media_server_url = environment.getProperty("mcs8.streamingMediaServer");
        group_id = environment.getProperty("mcs8.groupId");
        user = environment.getProperty("mcs8.adminUser");
        password = environment.getProperty("mcs8.password");
    }

    private static Mcs8Cilent mcs8Cilent;

    public static Mcs8Cilent getInstant() {
        if (mcs8Cilent == null) {
            mcs8Cilent = new Mcs8Cilent();
        }
        return mcs8Cilent;
    }

    private String webapi_url;
    private String streaming_media_server_url;
    private String group_id;
//    private static final String group_id = "12695";

//    private static final String webapi_url = "http://118.25.122.20:7712/";
//    private static final String streaming_media_server_url = "http://118.25.122.20:7711/api/postData";
//    private static final String group_id = "21";

    private String user = "AHWSPC";
    private String password = "000000";

    private static final String token_url = "api/v1/login";
    private static final String dev_list_url = "api/v1/DevList";
    private static final String history_file_list_url = "api/GetRecordFileListByUploadTime";



    private String token = "";

    @Scheduled(cron = "0 0 */24 * * ?")
    private void clearToken() {
        token = null;
    }


    /**
     * 获取token
     *
     * @return
     */
    private String getToken(String uid, String pwd) {
        String ret = HttpUtil.get(webapi_url + token_url + "?uid=" + uid + "&pwd=" + pwd);
        RetDate retDate = JSONUtil.toBean(ret, RetDate.class);
        if (retDate != null && retDate.getResult() == 200 && retDate.getContent() != null) {
            Map<String, Object> map = (Map) retDate.getContent();
            token = map.get("token").toString();
        }
        return token;
    }

    public String getToken() {
        if (StringUtils.isEmpty(token)) {
            token = getToken(user, password);
        }
        return token;
    }

    /**
     * 获取所有设备列表
     *
     * @return
     */
    public List<DeviceVo> getDeviceList(String groupId) {
        groupId = group_id;
        List<DeviceVo> deviceVos = new ArrayList<>();
        StringBuffer params = new StringBuffer();
        params.append("token").append("=").append(getToken());
        params.append("&").append("groupId").append("=").append(groupId);
        params.append("&").append("page").append("=").append(1);
        params.append("&").append("pageSize").append("=").append(50);
        String ret = HttpUtil.get(webapi_url + dev_list_url + "?" + params);
        RetDate retDate = JSONUtil.toBean(ret, RetDate.class);
        if (retDate != null && retDate.getResult() == 200 && retDate.getContent() != null) {
            List<Map<String, Object>> list = (List) retDate.getContent();
            for (Map<String, Object> temp : list) {
                //删除的设备,调度账号直接忽略
                if ((boolean) temp.get("isDeleted") || temp.get("deviceType").toString().equals("2")) {
                    continue;
                }
                DeviceVo deviceVo = new DeviceVo();
                deviceVo.setDevId(temp.get("deviceId").toString());
                deviceVo.setDeviceName(temp.get("deviceName").toString());
                deviceVo.setDeviceType(Integer.parseInt(temp.get("deviceType").toString()));
                deviceVo.setEnterId(Integer.parseInt(temp.get("enterId").toString()));
                deviceVo.setGroupId(Integer.parseInt(temp.get("groupId").toString()));
                deviceVo.setStatus(Integer.parseInt(temp.get("status").toString()));
                deviceVos.add(deviceVo);
            }
        }
        return deviceVos;
    }

    /**
     * 获取历史文件列表
     *
     * @return
     */
    public List<String> getHistoryFileList(String deviceId, String stime, String etime, int page, int pageSize) {
        List<String> files = new ArrayList<>();
        try {
            StringBuffer params = new StringBuffer();
            params.append("SessionId").append("=").append(getToken());
            params.append("&").append("st").append("=").append(stime);
            params.append("&").append("et").append("=").append(etime);
            if (StringUtils.isNotEmpty(deviceId)) params.append("&").append("did").append("=").append(deviceId);
            params.append("&").append("ft").append("=").append(3);
            params.append("&").append("lt").append("=").append(-1);
            params.append("&").append("page").append("=").append(page);
            params.append("&").append("pageSize").append("=").append(pageSize);
            String ret = HttpUtil.get(webapi_url + history_file_list_url + "?" + params.toString());
            RetDate retDate = JSONUtil.toBean(ret, RetDate.class);
            if (retDate.data != null) {
                List<Map<String, Object>> list = (List) retDate.getData();
                for (Map<String, Object> temp : list) {
                    String path = temp.get("path").toString();
                    String ip = temp.get("ip").toString();
                    String port = temp.get("port").toString();
                    files.add("http://" + ip + ":" + port + path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return files;
    }

    /**
     * @param dev_id
     * @param storType 0，本地录像 1、中心录像 2、中心和本地都录像
     * @return
     */
    public int startRecording(String dev_id, int storType) {
        Map<String, Object> map = new HashMap<>();
        map.put("devId", dev_id);
        map.put("storType", storType);
        int errorCount = 0;
        while (errorCount++ < 5) {
            RetDate retDate = callStreamingMediaServer(Method.STARTRECORD, map);
            logger.info("start dev_id:" + dev_id + ">" + retDate);
            if (retDate.getResult() == 200) {
                break;
            } else {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return 1;
    }

    public int stopRecording(String dev_id, int storType) {
        int errorCount = 0;
        Map<String, Object> map = new HashMap<>();
        map.put("devId", dev_id);
        map.put("storType", storType);
        while (errorCount++ < 5) {
            RetDate retDate = callStreamingMediaServer(Method.STOPRECORD, map);
            logger.info("start dev_id:" + dev_id + ">" + retDate);
            if (retDate.getResult() == 200) {
                break;
            } else {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return 1;
    }

    public RetDate callStreamingMediaServer(Method method, Map<String, Object> map) {
        RetDate retDate = new RetDate();
        Map<String, Object> params = new HashMap<>();
        params.put("request", true);
        params.put("id", 705224408);
        params.put("method", method.getKey());
        params.put("data", map);
        try {
            String ret = HttpUtil.post(streaming_media_server_url + "?token=" + getToken(), JSONUtil.toJsonStr(params));
            Map<String, Object> mm = JSONUtil.toBean(ret, Map.class);
            retDate.setResult(Integer.parseInt(mm.get("error").toString()));
            retDate.setMessage(mm.get("message").toString());
            retDate.setContent(mm.get("data"));
        } catch (Exception e) {
            e.printStackTrace();
            retDate.setResult(500);
            retDate.setMessage("请联系管理员，排查问题");
        }


        return retDate;
    }

    /**
     * 请求返回
     */
    @Data
    class RetDate {
        private int result;
        private String message;
        private Object content;

        // 请求结果返回值 data
        private Object data;
    }

    enum Method {
        STARTRECORD("startRecord", "开启录像"),
        STOPRECORD("stopRecord", "停止录像");

        private String key;
        private String memo;

        Method(String key, String memo) {
            this.key = key;
            this.memo = memo;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }
    }

}
